package com.netty.test.server;
 
import com.netty.model.LogonPacket;
import com.netty.model.Util;
import com.netty.task.LoginTask;
import com.netty.task.Task;
import com.netty.task.TaskFactory;
import com.netty.task.TaskManager;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
 
public class MyDecoder extends ChannelInboundHandlerAdapter{
    
    
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("server channelRead..");
        ByteBuf buffer = (ByteBuf) msg;
        System.out.println("readable length" + buffer.readableBytes());
        if (buffer.readableBytes() >= 8) {
        	byte[] totalLengthBuffer = new byte[4];
        	buffer.markReaderIndex();
        	buffer.readBytes(totalLengthBuffer);
        	buffer.resetReaderIndex();
        	
        	int length = Util.bytes2int(totalLengthBuffer, 0);
        	System.out.println("packet length" + length);
        	
        	if (length <= buffer.readableBytes()) {
        		byte[] receivedData = new byte[length];
        		buffer.readBytes(receivedData);
        		Task task = TaskFactory.createTaskByType(receivedData);
        		task.setContext(ctx);
        		TaskManager.INSTANCE.addTask(task);
        	}
        }
        
    }
    
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
 
}
